package com.liyunc.demo.resources;
/**
 * Copyright (c) 2018-2022 ThunderSoft
 * All Rights Reserved by Thunder Software Technology Co., Ltd and its affiliates.
 * You may not use, copy, distribute, modify, transmit in any form this file
 * except in compliance with ThunderSoft in writing by applicable law.
 */

import com.liyunc.demo.model.dto.FileInfoDto;
import com.liyunc.demo.model.dto.GenericDto;
import com.liyunc.demo.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author
 * @version 1.0
 * @file
 * @brief
 * @details
 * @date 2022-02-18
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2022-02-18                       Created
 */
@RestController
@RequestMapping(value = "/api/v1/file", produces = {MediaType.APPLICATION_JSON_VALUE})
public class FileResource {

    @Autowired
    private FileService fileService;

    @PostMapping(value = "", produces = {MediaType.APPLICATION_JSON_VALUE})
    public GenericDto<FileInfoDto> createFile(
        @RequestParam("file") MultipartFile file,
        @RequestParam("projectId") long projectId
    ) {
        if (file.isEmpty()) {
            return GenericDto.of(1, "upload fail", null);
        } else {
            try {
                FileInfoDto dto = fileService.createFile(file, projectId).orElse(null);
                return GenericDto.of(dto);
            } catch (IOException exception) {
                return GenericDto.of(1, "upload fail", null);
            }
        }
    }
}
